package com.app.socketclient;

import android.os.Handler;
import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Created Date 2019/5/20
 *
 * @author liangkun
 * description：
 */
public class SocketClientThread extends Thread {
    private Handler handler;

    public SocketClientThread(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void run() {
        while (true) {
            try {
                //创建Socket对象
                Socket socket = new Socket("localhost", 8888);
                //根据输入输出流和服务端连接
                OutputStream outputStream = socket.getOutputStream();//获取一个输出流，向服务端发送信息
                PrintWriter printWriter = new PrintWriter(outputStream);//将输出流包装成打印流
                printWriter.print("验证心跳");
                printWriter.flush();
                socket.shutdownOutput();//关闭输出流

                InputStream inputStream = socket.getInputStream();//获取一个输入流，接收服务端的信息
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);//包装成字符流，提高效率
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);//缓冲区
                String s = bufferedReader.readLine();
                if (!TextUtils.isEmpty(s)) {
                    DebugLog.d("SOCKET-PP " + "客户端接收服务端发送信息：" + s);
                    handler.sendEmptyMessage(10001);
                }

                //关闭相对应的资源
                bufferedReader.close();
                inputStream.close();
                printWriter.close();
                outputStream.close();
                socket.close();

            } catch (IOException e) {
                e.printStackTrace();
                DebugLog.d("SOCKET-PP " + "异常--：" + e.getMessage());
                handler.sendEmptyMessage(10086);

            }
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
